package com;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class ExcelImport {

    public static void main(String[] args) throws FileNotFoundException {
        String fileName = "G:\\IdeaProjects\\my-java-project\\dc-java\\src\\test\\java\\11.xlsx";
        new ExcelImport().importExcel(fileName);
    }

    public String importExcel(String fileName) throws FileNotFoundException {

        FileInputStream input = new FileInputStream(fileName);

        String message = "Import success";
        boolean isE2007 = false;
        //判断是否是excel2007格式
        if (fileName.endsWith("xlsx")) {
            isE2007 = true;
        }

        int rowIndex = 0;
        try {
            Workbook wb;
            //根据文件格式(2003或者2007)来初始化
            if (isE2007) {
                wb = new XSSFWorkbook(input);
            } else {
                wb = new HSSFWorkbook(input);
            }
            Sheet sheet = wb.getSheetAt(0);    //获得第一个表单

            int beginRow = ExcelUtil.getRowNum(wb, "t1_begin");
            int endRow = ExcelUtil.getRowNum(wb, "t1_end");
            List<FightInfo> list = new ArrayList<>();

            log.info("t1_begin={},t1_end={}", beginRow, endRow);

            for (int i = beginRow + 1; i < endRow - 1; i++) {
                rowIndex = i;
                Row row = sheet.getRow(i);
                Map<Integer, String> map = new HashMap<>();
                Integer index = 1;
                if (row == null) {
                    continue;
                }
                int cols = row.getLastCellNum();
                for (int j = 3; j < cols; j++) {
                    String value;
                    if (ExcelUtil.isMergedRegion(sheet, i, j)) {
                        value = ExcelUtil.getMergedRegionValue(sheet, i, j);
                    } else {
                        Cell cell = row.getCell(j);
                        value = cell.getStringCellValue();
                    }
                    map.put(index++, value);
                }
                FightInfo fightInfo = new FightInfo();
                fightInfo.setName(map.get(1));
                fightInfo.setRemark(map.get(2));
                fightInfo.setAdvage(map.get(3));
                list.add(fightInfo);
            }
            log.info("===>{}", list);
        } catch (Exception ex) {
            message = "Import failed, please check the data in " + rowIndex + " rows ";
            System.out.println(ex.getMessage());
        }
        return message;
    }


}
